package com.itlaoqi.rabbitmq.basic;

import com.itlaoqi.rabbitmq.utils.RabbitConstant;
import com.itlaoqi.rabbitmq.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //connectionFacotry用于创建MQ的物理连接
//        ConnectionFactory connectionFactory = new ConnectionFactory();
//        connectionFactory.setHost("192.168.10.10");//
//        connectionFactory.setPort(5672);//是rabbitmq的默认端口号
//        connectionFactory.setUsername("itlaoqi");
//        connectionFactory.setPassword("123456");
//        connectionFactory.setVirtualHost("/test");
        //TCP的物理连接
        Connection conn = RabbitUtils.getConnection();

        Channel channel = conn.createChannel();
        channel.queueDeclare(RabbitConstant.QUEUE_HELLOWORLD,false,false,false,null);

        //创建一个消息消费者
        //第二个参数代表是否自动确认收到消息,false代表手动编辑来确认消息接受
        //第三个参数传入DefaultConsumer的实现类
        channel.basicConsume(RabbitConstant.QUEUE_HELLOWORLD,false,new Reciver(channel));
    }
}

class Reciver extends DefaultConsumer{

    private Channel channel;
    //重写构造函数,Channel通道对象需要从外层传入，再HandleDelivery中要用到
    public Reciver(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        String message = new String(body);
        System.out.println("消费者接受到:::" + message);
        //签收消息，确认消息
        //envelope.getDeliveryTage(),获取这个消息的TagId
        //false 只确认签收当前的消息，设置为true的是则代表签收改消费者所有未签收的消息
        channel.basicAck(envelope.getDeliveryTag(), false);
    }
}
